const jwt = require('jsonwebtoken');
const path = require('path');
const { readFileSync } = require('fs');
const xy = require('../utils/xy')
module.exports = (req, resp, next) => {
    // 规定令牌必须从请求头传递进来
    if (!req.headers.authorization) {
        // resp.json({
        //     error_code: '406',
        //     msg: '缺少身份验证！'
        // })
        xy(resp, 406, '缺少身份验证！')
        return
    }
    // 拼接配置文件路径
    let configFilePath = path.join(__dirname, '../', 'config', 'config.json')
    let salt = JSON.parse(readFileSync(configFilePath, 'utf-8')).tokenSalt
    // console.log(salt)
    jwt.verify(req.headers.authorization, salt, (err, decoded) => {
        // console.log(err);
        if (err) {
            // resp.json({
            //     error_code: '407',
            //     msg: '身份验证失败！'
            // })
            xy(resp, 407, '身份验证失败！')
            return
        }
        // 验证令牌有效期
        let { startTime, expires } = decoded
        if (startTime + expires < +new Date()) {
            xy(resp, 408, '登录过期！')
            return
        }
        next()
    })
}